import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import 'controllers/analytics_controller.dart';
import 'controllers/emotion_controller.dart';
import 'controllers/history_controller.dart';
import 'controllers/home_controller.dart';
import 'controllers/record_controller.dart';
import 'controllers/record_detail_controller.dart';
import 'controllers/settings_controller.dart';
import 'core/constants/app_constants.dart';
import 'core/routes/app_routes.dart';
import 'core/theme/app_theme.dart';
import 'data/models/app_settings.dart';
import 'data/services/database_service.dart';

/// 应用程序入口
/// Application entry point
void main() async {
  // 确保Flutter绑定初始化
  // Ensure Flutter binding is initialized
  WidgetsFlutterBinding.ensureInitialized();

  // 设置系统UI样式
  // Set system UI style
  await _setupSystemUI();

  // 初始化核心服务
  // Initialize core services
  await _initializeServices();

  // 运行应用
  // Run the app
  runApp(const EmotionRecordApp());
}

/// 设置系统UI样式
/// Setup system UI style
Future<void> _setupSystemUI() async {
  // 设置状态栏样式
  // Set status bar style
  SystemChrome.setSystemUIOverlayStyle(
    const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.dark,
      statusBarBrightness: Brightness.light,
      systemNavigationBarColor: Colors.white,
      systemNavigationBarIconBrightness: Brightness.dark,
    ),
  );

  // 设置支持的屏幕方向
  // Set supported screen orientations
  await SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);
}

/// 初始化核心服务
/// Initialize core services
Future<void> _initializeServices() async {
  try {
    // 初始化数据库服务
    // Initialize database service
    final databaseService = DatabaseService();

    // 重置数据库以解决表结构不匹配问题
    // Reset database to fix table structure mismatch
    print('🔄 重置数据库中... / Resetting database...');
    await databaseService.resetDatabase();
    print('✅ 数据库重置完成 / Database reset completed');

    Get.put(databaseService, permanent: true);

    // 初始化所有控制器
    // Initialize all controllers
    Get.put(SettingsController(), permanent: true);
    Get.put(HomeController(), permanent: true);
    Get.put(RecordController(), permanent: true);
    Get.put(EmotionController(), permanent: true);
    Get.put(HistoryController(), permanent: true);
    Get.put(AnalyticsController(), permanent: true);
    Get.lazyPut(() => RecordDetailController());

    print('✅ 核心服务初始化完成 / Core services initialized successfully');
  } catch (e) {
    print('❌ 核心服务初始化失败 / Core services initialization failed: $e');
    // 这里可以添加错误上报逻辑
    // Error reporting logic can be added here
  }
}

/// 情绪记录应用主类
/// Main emotion record application class
class EmotionRecordApp extends StatelessWidget {
  const EmotionRecordApp({super.key});

  @override
  Widget build(BuildContext context) {
    // 使用 ScreenUtilInit 包装应用以支持屏幕适配
    // Use ScreenUtilInit to wrap the app for screen adaptation
    return ScreenUtilInit(
      // 设计稿尺寸 (基于 iPhone 14 Pro: 393x852)
      // Design size (based on iPhone 14 Pro: 393x852)
      designSize: const Size(412, 896),
      // 最小文本适配
      // Minimum text adaptation
      minTextAdapt: true,
      // 支持分屏模式
      // Support split screen mode
      splitScreenMode: true,
      // 构建器
      // Builder
      builder: (context, child) {
        return GetMaterialApp(
          // 应用基本信息
          // App basic information
          title: AppConstants.appName,
          debugShowCheckedModeBanner: false,

          // 主题配置
          // Theme configuration
          theme: AppTheme.lightTheme,
          darkTheme: AppTheme.darkTheme,
          themeMode: _getThemeMode(),

          // 路由配置
          // Route configuration
          initialRoute: AppRoutes.splash,
          getPages: AppRoutes.getPages(),

          // 国际化配置
          // Internationalization configuration
          locale: _getLocale(),
          fallbackLocale: const Locale('zh', 'CN'),

          // 性能配置
          // Performance configuration
          builder: (context, child) {
            return MediaQuery(
              // 禁用系统字体缩放
              // Disable system font scaling
              data: MediaQuery.of(context).copyWith(
                textScaler: TextScaler.noScaling,
              ),
              child: child!,
            );
          },

          // 导航观察者
          // Navigation observer
          navigatorObservers: [
            _AppNavigatorObserver(),
          ],

          // 错误处理已移除，GetMaterialApp不支持errorBuilder参数
          // Error handling removed, GetMaterialApp doesn't support errorBuilder parameter

          // 默认过渡动画
          // Default transition animation
          defaultTransition: Transition.cupertino,
          transitionDuration: const Duration(milliseconds: 300),

          // 启用日志
          // Enable logging
          enableLog: true,
          logWriterCallback: _logWriter,
        );
      },
    );
  }

  /// 获取主题模式
  /// Get theme mode
  ThemeMode _getThemeMode() {
    try {
      final settingsController = Get.find<SettingsController>();
      switch (settingsController.themeMode) {
        case AppThemeMode.light:
          return ThemeMode.light;
        case AppThemeMode.dark:
          return ThemeMode.dark;
        case AppThemeMode.system:
        default:
          return ThemeMode.system;
      }
    } catch (e) {
      // 如果设置控制器未初始化，使用系统主题
      // If settings controller is not initialized, use system theme
      return ThemeMode.system;
    }
  }

  /// 获取语言设置
  /// Get locale setting
  Locale _getLocale() {
    try {
      final settingsController = Get.find<SettingsController>();
      final languageCode = settingsController.language;

      switch (languageCode) {
        case 'en_US':
          return const Locale('en', 'US');
        case 'zh_CN':
        default:
          return const Locale('zh', 'CN');
      }
    } catch (e) {
      // 如果设置控制器未初始化，使用中文
      // If settings controller is not initialized, use Chinese
      return const Locale('zh', 'CN');
    }
  }

  /// 日志写入器
  /// Log writer
  void _logWriter(String text, {bool isError = false}) {
    if (isError) {
      print('🔴 GetX Error: $text');
    } else {
      print('🟢 GetX Log: $text');
    }
  }
}

/// 应用导航观察者
/// App navigator observer
class _AppNavigatorObserver extends NavigatorObserver {
  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPush(route, previousRoute);
    _logNavigation('Push', route.settings.name);
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPop(route, previousRoute);
    _logNavigation('Pop', route.settings.name);
  }

  @override
  void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
    _logNavigation('Replace', newRoute?.settings.name, oldRoute?.settings.name);
  }

  @override
  void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didRemove(route, previousRoute);
    _logNavigation('Remove', route.settings.name);
  }

  /// 记录导航日志
  /// Log navigation
  void _logNavigation(String action, String? routeName,
      [String? previousRoute]) {
    final message = previousRoute != null
        ? '$action: $previousRoute -> $routeName'
        : '$action: $routeName';
    print('🧭 Navigation: $message');
  }
}
